package com.xdl.flytest.service;

import com.xdl.flytest.bean.Task;
import com.xdl.flytest.dao.TaskMapper;
import com.xdl.flytest.util.docker.DockerManager;
import com.xdl.flytest.util.job.QuartzManager;
import com.xdl.flytest.util.job.TestCaseJob;
import com.xdl.flytest.util.job.TestSuitJob;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: 80736
 * @Date: 2019/1/28 18:38
 * @Description:
 */
@Service
public class TaskService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private QuartzManager quartzManager;

    public List<Task> selectTasks() {
        return taskMapper.selectTasks();
    }

    public void addTask(Task task) throws SchedulerException {

        //设置uuid到trigger内
        String uuid = DockerManager.getUUID();
        task.setTriggerName(uuid);
        task.setTriggerGroup(uuid);
        // 对比当前task和数据库内task是否重复，如果重复则跳过，不重复则添加新的task，并插入数据库
        Task existTask = taskMapper.selectByTaskNameAndJobGroup(task.getTaskName(), task.getRunWith());
        if (existTask != null) {
            logger.debug("job aready exist");
            return;
        }


        Date date;
        if ("TestCase".equalsIgnoreCase(task.getJobClass())) {
            date = quartzManager.addJob(task, TestCaseJob.class);
        } else if ("TestSuit".equalsIgnoreCase(task.getJobClass())) {
            date = quartzManager.addJob(task, TestSuitJob.class);
        } else {
            throw new RuntimeException("expect testcase or testsuit job but got another params");
        }

        task.setStatus(0);
        task.setCreateTime(date);
        taskMapper.insertSelective(task);
        quartzManager.printRamJob();
    }

    public Task getTaskById(Integer id) {
        return taskMapper.selectByPrimaryKey(id);
    }


    /**
     * 更新定时任务
     *
     * @param task
     */
    public void updateTask(Task task) {
        quartzManager.modifyJobTime(task);
        taskMapper.updateByPrimaryKeySelective(task);
    }

    public void deleteTask(Integer id) {
        Task task = taskMapper.selectByPrimaryKey(id);
        quartzManager.removeJob(task);
        taskMapper.deleteByPrimaryKey(id);
    }

    public boolean runTaskNow(Integer id) throws SchedulerException {

        Task task = taskMapper.selectByPrimaryKey(id);
        String uuid = DockerManager.getUUID();
        switch (task.getJobClass()) {
            case "TestCase":
                quartzManager.runningNow(task, TestCaseJob.class, uuid);
                break;
            case "TestSuit":
                quartzManager.runningNow(task, TestSuitJob.class, uuid);
                break;
        }

        return true;
    }

    public boolean stopTask(Integer id) {
        Task task = taskMapper.selectByPrimaryKey(id);
        try {
            quartzManager.pauseJob(task);
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean restartTask(Integer id) {
        Task task = taskMapper.selectByPrimaryKey(id);
        try {
            quartzManager.resumeJob(task);
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 运行内存中所有job
     */
    public void runAllJob() {
        quartzManager.startJobs();
    }

    /**
     * 暂停所有job
     */
    public void pauseAllJob() {
        quartzManager.shutdownJobs();
    }
}
